// thunk去做接口请求
import http from "@/utils/http";
import {createAction} from 'redux-actions'
import {LOGINACTION, LOGOUT} from "@/store/actionTypes";
import {clearToken, setToken} from "@/utils/token";

// 触发reducer的action函数==>实现数据更新
export const fetchLoginAction = createAction(LOGINACTION)
export const logOutAction = createAction(LOGOUT)

//-----------------------------------------------------------
// 触发thunk的action函数
export function fetchLogin(values) {
  return async dispatch => {
    //    做什么事情
    // const res = await loginReq(values)
    const res = await http.post('/authorizations', values)
    // console.log(res)
    dispatch(fetchLoginAction(res.data))
    // 本地存储里面再存一份=> 持久化
    setToken(res.data)
  }
}

// 触发函数
export const fetchCode = mobile => {
  return async () => { // 不需要接受disaptch
    await http.get(`/sms/codes/${mobile}`);
  }
}

// 退出登录的action
export const fetchLogOut = () => {
  return dispatch => {
    //  清空redux里面的token
    //派发action对象去修改store，通过reducer
    dispatch(logOutAction())
    //  清空本地存储token
    clearToken()
  }
}
